package com.binance.zkconfig.register;

import com.binance.zkconfig.config.ZkConfiguration;
import com.binance.zkconfig.processor.ZkPropertySourcesProcessor;
import com.binance.zkconfig.processor.ZkValueAnnotationProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Objects;

/**
 * Created by Fei.Huang on 2018/8/29.
 */
public class ZkConfigRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 顺序不可变
        registerBean(ZkPropertySourcesProcessor.class, registry);
        registerBean(ZkConfiguration.class, registry);
        registerBean(ZkValueAnnotationProcessor.class, registry);
    }

    private static boolean registerBean(Class<?> beanClass, BeanDefinitionRegistry registry) {
        if (registry.containsBeanDefinition(beanClass.getName())) {
            return false;
        }
        String[] candidates = registry.getBeanDefinitionNames();
        for (String candidate : candidates) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
            if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {
                return false;
            }
        }
        BeanDefinition annotationProcessor = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();
        registry.registerBeanDefinition(beanClass.getName(), annotationProcessor);
        return true;
    }
}